/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bbd.crawler.job.fwk;

import bbd.crawler.dp.DataProcessorFactory;
import bbd.crawler.dp.fwk.ProcessorInterface;
import bbd.crawler.util.Console;

import bbd.crawler.xml.XMLHandlerFactory;
import bbd.crawler.xml.handler.fwk.BaseXMLHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 *
 * @author amochakr
 */
public abstract class BaseJob implements JobInterface {

    //--------------------------------------------------------------------------
    /** Javadoc here */
    protected final Object processUrl ( String url ) throws Exception {

        Object data = null;

        SAXParser xmlParser = SAXParserFactory.newInstance().newSAXParser();

        BaseXMLHandler xmlHandler = XMLHandlerFactory.getHandlerFor (url);

        if ( xmlHandler != null ) {

            xmlParser.parse ( url, xmlHandler );

            if ( xmlHandler.isDataLoaded() ) {

                if ( xmlHandler.isProcessorAvailable() ) {

                    ProcessorInterface processor =
                                            DataProcessorFactory.getProcessor (
                                                                        xmlHandler.getClass().getName()
                                                                    );

                    if ( processor != null ) {

                        processor.process ( xmlHandler.getParsedData() );

                        data = processor.getProcessedData();
                    }
                }
                else {

                    data = xmlHandler.getParsedData();
                }
            }
            else {

                Console.debug ( "BaseJob.processUrl", "No Data loaded for " + url );
            }

            Console.debug (
                        "BaseJob.processUrl",
                        "Handler { " +
                        "loaded data: " + xmlHandler.isDataLoaded() +
                        " | has processor: " + xmlHandler.isProcessorAvailable() +
                        " | data: " + ( data == null ? "NULL" : "not null" ) + " }"
                     );
        }
        else {

            Console.debug ( "BaseJob.processUrl", "No Handler mapped for " + url );
        }

        return data;

    } // end method processUrl

} // end class BaseJob
